import Vue from 'vue'
import Vuex from 'vuex'
import { Message, Notification } from 'element-ui'

import Router, { resetRouter } from '@/router'
import { USER_TOKEN } from '@/utils/constant'
import { removeLocalStorageItem } from '@/utils/storage-helper'
import { getUserInfo, logout } from '@/services/model/user'
import { mutations as menuMutaions } from '../views/layout/collapse.store'
Vue.use(Vuex)

export default new Vuex.Store({
    state: {
        refreshMap: {}, // 当前激活的时间戳，用于手动刷新路由
        userInfo: {
            // accountType	账号类型 1-系统管理员 2-系统管理员子用户 3-租户管理员 4-租户管理员子用户
        }, // 用户信息
        menuList: [], // 动态生成的菜单列表
        nodeList: [], // 从后端取到的原始DSL描述
        webList: [], // 从后端取到的原始DSL描述
        addRouter: [], // 动态挂在的路由
        pagination: {
            current: 1,
            total: 0,
            pageSize: 10, // 每页中显示10条数据
            showSizeChanger: true,
            pageSizeOptions: ['10', '20', '50'], // 每页中显示的数据
            // showTotal: total => `共有 ${total} 条数据`, // 分页中显示总的数据
        },
        newDataList: [], // 最新数据
        ws: '',
    },
    getters: {
        // 姓名
        name (store) {
            return store.userInfo.name
        },
        // 用户名
        username (store) {
            return store.userInfo.userName
        },
        userId (store) {
            return store.userInfo.id
        },
        // 账号类型 1-系统管理员 2-系统管理员子用户 3-租户管理员 4-租户管理员子用户
        accountType (store) {
            return store.userInfo.accountType
        },
        // 已经拥有的map权限
        hasRouterMap (store) {
            return (store.addRouter || []).map(x => x.path)
        },
        // 拥有访问的菜单权限
        hasMEnuList (store) {
            let list = []
            store.menuList.map(x => {
                if ((x.children || []).length) {
                    x.children.map(y => list.push(y.path))
                } else list.push(x.path)
            })
            return list
        },
    },
    mutations: {
        // 登出处理
        _logOut (state) {
            state.ws && state.ws.close()// 关闭websoket连接
            resetRouter()
            // 清楚token
            removeLocalStorageItem(USER_TOKEN)
            state.menuList = []
            state.addRouter = null
            Router.push('/login')
            menuMutaions.clearSessionStorage()
        },
        setState (state, { name, value }) {
            state[name] = value
        },
        // 更新当前的路由
        refreshCurrentRoute: (state, url) => {
            // 在对象中直接给属性赋值，vue中不会监测到变化
            // state.refreshMap[url] = Date.parse(new Date())
            state.refreshMap = Object.assign({}, state.refreshMap, { [url]: Date.parse(new Date()) })
        },
        setNewData (state, payload) { // 最新数据
            state.newDataList = payload
        }
    },
    actions: {
        // 查询用户信息
        async queryUserInfo ({ commit, dispatch }) {
            let { data } = await getUserInfo()
            commit('setState', { name: 'userInfo', value: data || {} })
            // socket数据
            // dispatch('getNewData')
        },
        // 登出
        logout ({ commit, state }) {
            // state.addRouter !== null && logout()
            Router.push('/login')
        },
        // websoket
        getNewData ({ commit, state, getters }) {
            if ('WebSocket' in window) {
                let userId = getters.userId
                // 打开一个 web socket
                // 贵州高速公路集团
                // let ws = new WebSocket(`ws://8.134.54.223:16001/webSocket/recentList/${userId}`)
                // 贵州茅台酒股份有限公司
                // let ws = new WebSocket(`ws://8.134.54.223:16002/webSocket/recentList/${userId}`)
                // 边坡云
                let ws = new WebSocket(`ws://8.134.54.223:16000/webSocket/recentList/${userId}`)
                state.ws = ws
                ws.onopen = function () {
                    console.log('websocket 连接上')
                }// 连接
                ws.onmessage = function (evt) {
                    let infoDataType = JSON.parse(evt.data).type
                    let infoData = JSON.parse(evt.data).data
                    if (infoDataType === 2) { // 报警提示
                        Notification({
                            title: '预警提示',
                            type: 'warning',
                            dangerouslyUseHTMLString: true,
                            message: `<a> ${infoData.projectName}-${infoData.workPointName}-
              ${infoData.monitorTypeName}-${infoData.warningLevelName}</a>`,
                            duration: 5000,
                            onClick: function () {
                                Router.push({
                                    path: `/project/${infoData.projectId}/work-point/${infoData.workPointId}/monitor/${infoData.monitorType}?activeId=${infoData.monitorPointId}`
                                })
                            }
                        })
                    }
                    commit('setNewData', JSON.parse(evt.data))
                }// 接收消息
                ws.onclose = function (e) { // 监听关闭
                    // console.log(e)
                    ws.close()
                    console.log('连接已关闭...')
                }
                ws.onerror = function (err) {
                    // console.log(err)
                }
            } else {
                // 浏览器不支持 WebSocket
                Message({
                    type: 'warning',
                    message: '您的浏览器不支持 WebSocket!'
                })
            }
        },
    }
})
